package com.xxxx.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.xxxx.dto.PageBean;
import com.xxxx.mapper.EmployeeMapper;
import com.xxxx.pojo.*;
import com.xxxx.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chao
 * @since 2022-09-26
 */
@RestController
@RequestMapping("/employee/basic/")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private PoliticsStatusService politicsStatusService;

    @Autowired
    private JoblevelService joblevelService;

    @Autowired
    private NationService nationService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @ApiOperation(value = "获取所有员工（分页）")
    @GetMapping("/")
    public PageBean getEmployees(@RequestParam(defaultValue = "1") Integer currentPage,
                                 @RequestParam(defaultValue = "10") Integer size,
                                 Employee employee, LocalDate[] beginDateScope) {
        return employeeService.getEmployeeByPage(currentPage, size, employee, beginDateScope);
    }

    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/politicsStatus")
    public R getAllPolitics() {
        List<PoliticsStatus> politicsStatuses = politicsStatusService.list();
        return R.success(politicsStatuses);
    }

    @ApiOperation(value = "获取所有职称")
    @GetMapping("/joblevels")
    public R getJoblevel() {
        List<Joblevel> list = joblevelService.list();
        return R.success(list);
    }

    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nations")
    public R getNations() {
        List<Nation> list = nationService.list();
        return R.success(list);
    }

    @ApiOperation(value = "获取所有职位")
    @GetMapping("/positions")
    public R getPositions() {
        List<Position> list = positionService.list();
        return R.success(list);
    }

    @ApiOperation(value = "获取所有部门")
    @GetMapping("/departments")
    public R getDepartments() {
        List<Department> list = departmentService.getAllDepartmentList();
        return R.success(list);
    }


    @ApiOperation(value = "获取工号")
    @GetMapping("/maxWorkId")
    public R maxWorkId() {
        return R.success(employeeService.maxWorkId());
    }

    @ApiOperation(value = "添加员工")
    @PostMapping("/")
    public R saveEmployee(@RequestBody Employee employee) {

        return employeeService.saveEmp(employee);
    }

    @ApiOperation(value = "更新员工")
    @PutMapping("/")
    public R updateEmployee(@RequestBody Employee employee) {
        boolean flag = employeeService.updateById(employee);
        return flag ? R.success("更新员工成功！") : R.error("更新员工失败！");
    }

    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public R deleteEmployee(@PathVariable("id") Integer id) {
        boolean flag = employeeService.removeById(id);
        return flag ? R.success("删除成功！") : R.error("删除失败！");
    }

    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response) {
        List<Employee> list = employeeService.getEmployee(null);
        ExportParams exportParams = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Employee.class, list);
        ServletOutputStream out = null;
        try {
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("" +
                    "员工表.xls", "UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @ApiOperation(value = "导入员工数据")
    @PostMapping("/import")
    public R importEmployee(MultipartFile file) {
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Nation> nations = nationService.list();
        List<PoliticsStatus> politicsStatuses = politicsStatusService.list();
        List<Position> positions = positionService.list();
        List<Department> departments = departmentService.list();
        List<Joblevel> joblevels = joblevelService.list();
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            list.forEach(employee -> {
                //民族id
                employee.setNationId(nations.get(nations.indexOf(new Nation(employee.getNation().getName()))).getId());
                //政治面貌id
                employee.setPoliticId(politicsStatuses.get(politicsStatuses.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                //部门id
                employee.setDepartmentId(departments.get(departments.indexOf(new Department(employee.getDepartment().getName()))).getId());
                //职称id
                employee.setJobLevelId(joblevels.get(joblevels.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                //职位id
                employee.setPosId(positions.get(positions.indexOf(new Position(employee.getPosition().getName()))).getId());
                employee.setWorkID(employeeService.maxWorkId());
            });
            if (employeeService.saveBatch(list)) {
                return R.success("导入成功");
            }
            return R.error("导入失败");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error("导入失败");
    }
}
